package _image

import (
	"beesoft.ink/application/media/app/helper/helper"
	"image"
	"image/color"
	"image/draw"
	"io"
)

var Image = &imageHelper{
	Type: "jpeg",
	Jpeg: &jpegHelper{},
	Png:  &pngHelper{},
	Gif:  &gifHelper{},
}

type imageHelper struct {
	Type    string
	Quality int
	Jpeg    *jpegHelper
	Png     *pngHelper
	Gif     *gifHelper
}

func (r imageHelper) Convert(reader io.Reader, writer io.Writer) {
	img, err := r.Decode(reader)
	if err != nil {
		helper.Log("Error", "Decode Error")
	}

	newImg := image.NewRGBA(img.Bounds())
	draw.Draw(newImg, newImg.Bounds(), &image.Uniform{
		C: color.White,
	}, image.Point{}, draw.Src)
	draw.Draw(newImg, newImg.Bounds(), img, img.Bounds().Min, draw.Over)

	err = r.Encode(writer, newImg)
	if err != nil {
		helper.Log("Error", "Encode Error")
	}
}
func (r imageHelper) Compress(reader io.Reader, writer io.Writer) {
	img, err := r.Decode(reader)
	if err != nil {
		helper.Log("Error", "Decode Error")
	}

	err = r.Encode(writer, img)
	if err != nil {
		helper.Log("Error", "Encode Error")
	}
}
func (r imageHelper) Options(reader io.Reader) (image.Config, string, error) {
	return image.DecodeConfig(reader)
	// config.Width
	// config.Height
}

func (r imageHelper) Decode(reader io.Reader) (image.Image, error) {
	img, _, err := image.Decode(reader)
	return img, err
}
func (r imageHelper) Encode(writer io.Writer, img image.Image) error {
	var err error

	switch r.Type {
	case "png":
		err = r.Png.Encode(writer, img)
	case "gif":
		err = r.Gif.Encode(writer, img)
	case "jpeg":
		err = r.Jpeg.SetQuality(r.Quality).Encode(writer, img)
	}

	return err
}

func (r imageHelper) SetType(imageType string) imageHelper {
	r.Type = imageType
	return r
}
func (r imageHelper) SetQuality(quality int) imageHelper {
	r.Quality = quality
	return r
}

// img := image.NewGray()
// img := image.NewNRGBA()

// image.Point{X: width, Y: height}

// image.Rect(0, 0, width, height)
// image.Rectangle{Max}

// img.At(x, y)
// img.Set(x, y, color)
// img.SetGray(x, y, color.Gray{Y})

// pi := image.NewPaletted(im.Bounds(), []color.Color{
// 	color.Gray{Y: 255},
// })
// draw.FloydSteinberg.Draw(pi, img.Bounds(), img, image.ZP)

// c := color.GrayModel.Convert().(color.Gray)
// color.NRGBA{
// 	R: uint8((x + y) & 255),
// 	G: uint8((x + y) << 1 & 255),
// 	B: uint8((x + y) << 2 & 255),
// 	A: 255,
// }

// Black       = Gray16{0}
// White       = Gray16{0xffff}
// Transparent = Alpha16{0}
// Opaque      = Alpha16{0xffff}

// color
// CMYKToRGB
// RGBToCMYK
// RGBToYCbCr
// YCbCrToRGB

// Alpha
// Alpha16
// Gray
// Gray16
// RGBA
// RGBA64
// NRGBA
// NRGBA64
// CMYK
// NYCbCrA
//
// https://github.com/discord/lilliput
// https://github.com/disintegration/imaging
// https://github.com/foobaz/lossypng/
//
// replace (
// github.com/unidoc/unipdf/v3 => github.com/lianggx6/unipdf v0.0.0-20200409043947-1c871b2c4951
// )
